
package com.kanjian.music.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import com.kanjian.music.entity.Music;

public class MusicDownloader {

    public boolean mIsPause;

    public final static int DOWNLOAD_STATUS_SUCCESS = 0;

    public final static int DOWNLOAD_STATUS_USER_PAUSE = 1;

    public void downloadToFile(String filePath, Music music, MusicDownloadListener listener) {
        try {
            File tagFile = new File(filePath);
            MusicDownloadEntity entity;
            long downloadedSize = 0;
            if (tagFile.exists()) {
                downloadedSize = tagFile.length();
                entity = DownloadHelper.getInputStreamFromUrl(music.getMusicUrl(), downloadedSize);
            } else {
                entity = DownloadHelper.getInputStreamFromUrl(music.getMusicUrl());
            }
            if (entity.mInpustream != null) {
                byte[] buffer = new byte[1024 * 8];
                FileOutputStream fos = new FileOutputStream(tagFile, true);
                long downloadedLength = downloadedSize;
                int length = 0;
                int progress = 0;
                int lastProgress = 0;
                listener.onStartDownload(music);
                while ((length = entity.mInpustream.read(buffer)) != -1 && !mIsPause) {
                    downloadedLength += length;
                    fos.write(buffer, 0, length);
                    progress = (int) (downloadedLength * 100 / (entity.mContentLength + downloadedSize));
                    if (progress != lastProgress) {
                        if (listener != null) {
                            listener.onProgress(music, progress);
                        }
                    }
                    lastProgress = progress;
                }
                if (listener != null) {
                    if (mIsPause) {
                        listener.finishDownload(music, DOWNLOAD_STATUS_USER_PAUSE);
                    } else {
                        listener.finishDownload(music, DOWNLOAD_STATUS_SUCCESS);
                    }
                }
                fos.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pause() {
        mIsPause = true;
    }
}
